<!-- src/components/handsontable/index.vue -->
<template>
    <div class="page-container">
      <a-card>
        <template #title>{{ title }}</template>
        <template #extra>
          <slot name="extra">
            <a-button type="primary" @click="$emit('export')">导出</a-button>
          </slot>
        </template>
        
        <div class="table-container">
          <div class="table-header" v-if="showToolbar">
            <div class="left-actions">
              <slot name="leftActions">
                <a-button type="primary" @click="$emit('add')" v-if="enableAdd">
                  新增
                </a-button>
                <a-button 
                  danger 
                  @click="$emit('batch-delete', getSelectedData())" 
                  v-if="enableBatchDelete && selectedRows.size > 0"
                >
                  批量删除
                </a-button>
              </slot>
            </div>
            <div class="right-actions">
              <slot name="rightActions"></slot>
            </div>
          </div>
  
          <HotTable
            ref="hotTableRef"
            :settings="mergedSettings"
            :data="data"
          />
        </div>
      </a-card>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed } from 'vue';
  import { HotTable } from '@handsontable/vue3';
  import { registerAllModules } from 'handsontable/registry';
  import type { PropType } from 'vue';
  
  registerAllModules();
  
  // 定义组件属性
  const props = defineProps({
    title: {
      type: String,
      default: '数据列表'
    },
    data: {
      type: Array as PropType<any[]>,
      required: true
    },
    columns: {
      type: Array as PropType<any[]>,
      required: true
    },
    showToolbar: {
      type: Boolean,
      default: true
    },
    enableAdd: {
      type: Boolean,
      default: true
    },
    enableBatchDelete: {
      type: Boolean,
      default: true
    },
    enableDelete: {
      type: Boolean,
      default: true
    },
    enableDetail: {
      type: Boolean,
      default: true
    },
    settings: {
      type: Object,
      default: () => ({})
    }
  });
  
  // 定义事件
  const emit = defineEmits([
    'add',
    'delete',
    'batch-delete',
    'detail',
    'export',
    'selection-change'
  ]);
  
  // 选中的行
  const selectedRows = ref(new Set());
  const isAllSelected = ref(false);
  
  // 复选框渲染器
  const checkboxRenderer = (instance, td, row, col, prop, value, cellProperties) => {
    td.innerHTML = '';
    
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.checked = row === -1 ? isAllSelected.value : selectedRows.value.has(row);
    
    if (row === -1) {
      checkbox.onclick = (e) => {
        e.stopPropagation();
        isAllSelected.value = checkbox.checked;
        if (checkbox.checked) {
          const totalRows = instance.countRows();
          for (let i = 0; i < totalRows; i++) {
            selectedRows.value.add(i);
          }
        } else {
          selectedRows.value.clear();
        }
        instance.render();
        emitSelectionChange();
      };
    } else {
      checkbox.onclick = (e) => {
        e.stopPropagation();
        if (checkbox.checked) {
          selectedRows.value.add(row);
        } else {
          selectedRows.value.delete(row);
        }
        isAllSelected.value = selectedRows.value.size === instance.countRows();
        instance.render();
        emitSelectionChange();
      };
    }
    
    td.appendChild(checkbox);
    return td;
  };
  
  // 操作列渲染器
  const actionRenderer = (instance, td, row, col, prop, value, cellProperties) => {
    td.innerHTML = '';
    td.className = 'action-column';
    
    const container = document.createElement('div');
    container.className = 'action-container';
    container.addEventListener('mousedown', (e) => {
      e.stopPropagation();
    });
    
    if (props.enableDetail) {
      const detailBtn = document.createElement('button');
      detailBtn.innerHTML = '详情';
      detailBtn.className = 'btn-detail';
      detailBtn.onmousedown = (e) => {
        e.stopPropagation();
        e.preventDefault();
      };
      detailBtn.onclick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        emit('detail', instance.getSourceDataAtRow(row));
      };
      container.appendChild(detailBtn);
    }
    
    if (props.enableDelete) {
      const deleteBtn = document.createElement('button');
      deleteBtn.innerHTML = '删除';
      deleteBtn.className = 'btn-delete';
      deleteBtn.onmousedown = (e) => {
        e.stopPropagation();
        e.preventDefault();
      };
      deleteBtn.onclick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        emit('delete', instance.getSourceDataAtRow(row));
      };
      container.appendChild(deleteBtn);
    }
    
    td.appendChild(container);
    return td;
  };
  
  // 默认表格配置
  const defaultSettings = {
    height: 500,
    manualRowMove: true,
    className: 'htCenter',
    currentRowClassName: 'current-row',
    rowHeights: 40,
    columnHeaderHeight: 45,
    outsideClickDeselects: false,
    wordWrap: false,
    dropdownMenu: false,
    contextMenu: false,
    colHeaders: true,
    rowHeaders: false,
    stretchH: 'all'
  };
  
  // 合并表格配置
  const mergedSettings = computed(() => ({
    ...defaultSettings,
    ...props.settings,
    columns: [
      {
        title: '',
        renderer: checkboxRenderer,
        readOnly: true,
        width: 30
      },
      ...props.columns,
      {
        title: '',
        renderer: actionRenderer,
        readOnly: true,
        width: 150
      }
    ],
    licenseKey: 'non-commercial-and-evaluation'
  }));
  
  // 获取选中数据
  const getSelectedData = () => {
    return Array.from(selectedRows.value).map(rowIndex => props.data[rowIndex]);
  };
  
  // 发送选择变化事件
  const emitSelectionChange = () => {
    emit('selection-change', getSelectedData());
  };
  
  // 暴露方法给父组件
  defineExpose({
    getSelectedData,
    clearSelection: () => {
      selectedRows.value.clear();
      isAllSelected.value = false;
    }
  });
  </script>
  
  <style scoped>
  .page-container {
    padding: 24px;
    background: #f0f2f5;
    min-height: 100vh;
  }
  
  .table-container {
    width: 100%;
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .left-actions,
  .right-actions {
    display: flex;
    gap: 8px;
  }
  
  :deep(.ant-card) {
    border-radius: 8px;
  }
  
  :deep(.ant-card-head) {
    border-bottom: 1px solid #f0f0f0;
    padding: 0 24px;
  }
  
  :deep(.handsontable) {
    font-size: 14px;
  }
  
  :deep(.handsontable td) {
    padding: 4px 8px;
    border-color: #f0f0f0;
  }
  
  :deep(.handsontable th) {
    background-color: #fafafa;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    border-color: #f0f0f0;
  }
  
  :deep(.current-row) {
    background-color: #e6f7ff !important;
  }
  
  :deep(.action-column) {
    position: sticky !important;
    right: 0;
    background-color: white !important;
    box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
    z-index: 2;
  }
  
  :deep(.action-container) {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
  
  :deep(.btn-detail),
  :deep(.btn-delete) {
    padding: 4px 12px;
    font-size: 13px;
    border-radius: 4px;
    cursor: pointer;
    user-select: none;
  }
  
  :deep(.btn-detail) {
    background-color: #1890ff;
    color: white;
    border: none;
  }
  
  :deep(.btn-delete) {
    background-color: #ff4d4f;
    color: white;
    border: none;
  }
  
  :deep(.btn-detail:hover) {
    background-color: #40a9ff;
  }
  
  :deep(.btn-delete:hover) {
    background-color: #ff7875;
  }
  
  :deep(input[type="checkbox"]) {
    width: 16px;
    height: 16px;
    cursor: pointer;
    position: relative;
    top: 2px;
  }
  </style>